<template>
    <div>
      <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
             :on-remove="handleRemove"
            :http-request="uploadImg"
            :before-upload="beforeAvatarUpload">
            <img  v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
    </div>
</template>

<script>
export default {
  name: 'Imgcomponents',
  props: {
    img: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      imageUrl: ''
    }
  },
  methods: {
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    handleRemove () {},
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    uploadImg ({ file }) {
      console.log(file)
      var COS = require('cos-js-sdk-v5')

      // SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
      var cos = new COS({
        SecretId: 'AKIDnPlshFYaU7TZOxFG0TfaFciX5NOAgwxh',
        SecretKey: 'UifLkskKdfRwA6mCLEqBF2YonVv5ybx2'
      })

      cos.putObject({
        Bucket: 'hmmm-project-1309634948', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: file, // 上传文件对象
        onProgress: function (progressData) {
          // console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        if (err) return
        this.imageUrl = 'https://' + data.Location
        this.$emit('update:img', this.imageUrl)
      })
    }
  }
}
</script>

<style lang="scss" scoped>

// 图片上传样式
  ::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  ::v-deep.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  ::v-deep.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }
  ::v-deep.avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>
